package com.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 一、NIO三大核心
 *
 *
 * 1. 通道（Channel）：连接
 *     SelectableChannel:
 *        SocketChannel
 *        ServerSocketChannel
 *        DatagramChannel
 *
 *
 * 2. 缓冲区(Buffer)： 数据存取
 *
 * 3. 选择器(Selector): 是SelectableChannel的多路复用器， 用于监控SelectableChannel的IO情况
 */
public class TestBlockingNIO {

    /**
     * 服务端
     * @throws IOException
     */
    @Test
    public void testServer() throws IOException {

        ServerSocketChannel ssChannel = ServerSocketChannel.open();

        FileChannel outChannel = FileChannel.open(Paths.get("/Users/laocao/CompanyProject/StuSomeModel/copy/cglib-2.2.3.jar"),StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //绑定连接
        ssChannel.bind(new InetSocketAddress(8989));

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        SocketChannel sChannel = ssChannel.accept();

        while (sChannel.read(byteBuffer) != -1){
            byteBuffer.flip();
            outChannel.write(byteBuffer);
            byteBuffer.clear();
        }

        //发送反馈
        byteBuffer.put("服务端接收数据成功".getBytes());
        byteBuffer.flip();
        sChannel.write(byteBuffer);


        outChannel.close();
        sChannel.close();
        ssChannel.close();


        System.out.println("server");
    }

    /**
     * 客户端
     */
    @Test
    public void testClient() throws IOException {

        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8989));

        FileChannel inChannel = FileChannel.open(Paths.get("/Users/laocao/CompanyProject/StuSomeModel/copy/cglib-2.2.2.jar"), StandardOpenOption.READ);

        ByteBuffer bBuf = ByteBuffer.allocate(1024);

        while (inChannel.read(bBuf) != -1){
            bBuf.flip();
            //将文件写入SocketIO中
            sChannel.write(bBuf);
            bBuf.clear();
        }

        sChannel.shutdownOutput();

        //接收反馈
        int len = 0;
        while ((len = sChannel.read(bBuf)) != -1){
            bBuf.flip();
            System.out.println(new String(bBuf.array(), 0 , len));
            bBuf.clear();
        }

        inChannel.close();
        sChannel.close();

        System.out.println("client");
    }





}
